﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace DDD.GPT;

public sealed class ChatGptHttpClient
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;

    public ChatGptHttpClient(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _httpClient.BaseAddress = new Uri("https://api.openai.com/");

        var name = configuration["ChatGptKey"];
    }

    public async Task<string> Chat(string message)
    {
        if (string.IsNullOrEmpty(message))
            return "请输入问题";

        var input = new Input()
        {
            messages =
            [
                new Message { content = message }
            ]
        };

        var content = new StringContent(JsonConvert.SerializeObject(input));
        const string contentType = "Content-Type";
        content.Headers.Remove(contentType);
        content.Headers.Add(contentType, "application/json");

        var response = await _httpClient.PostAsync("v1/chat/completions", content);
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync();
        }

        return "请求失败，请稍后再重试";
    }
}

public record Input
{
    public string model { get { return "gpt-3.5-turbo"; } }

    public Message[] messages { get; init; }
}

public record Message
{
    public string role { get { return "user"; } }

    public string content { get; init; }
}
